<?php

class Avatar_AdminLevelController extends Core_Controller_Action_Admin {
	public function indexAction() {
		
		// Make navigation
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'avatar_admin_main', array (), 'avatar_admin_main_level' );
		$level_id = $this->_getParam ( 'level_id' );
		// Make form
		$this->view->form = $form = new Avatar_Form_Admin_Level ();
		
		if (! $this->getRequest ()->isPost ()) {
			if (null !== $level_id) {
				$permissionTable = $this->_helper->api ()->getDbtable ( 'permissions', 'authorization' );
				$select = $permissionTable->select ()->where ( 'level_id = ?', $level_id )->where ( 'type = ?', 'avatar' );
				$level_permissions = $permissionTable->fetchAll ( $select );
				$settings = array ();
				
				foreach ( $level_permissions as $avatar_permission ) {
					$settings [$avatar_permission->name] = $avatar_permission->value;
				}
				
				$settings = array_merge ( $settings, array ('level_id' => $level_id ) );
				
				$form->populate ( $settings );
			}
			
			return;
		}
		
		// Process form
		if ($this->getRequest ()->isPost () && $form->isValid ( $this->getRequest ()->getPost () )) {
			$level_id = $this->_getParam ( 'level_id' );
			$values = $form->getValues ();
			$permissionTable = $this->_helper->api ()->getDbtable ( 'permissions', 'authorization' );
			$select = $permissionTable->select ()->where ( 'level_id = ?', $level_id )->where ( 'type = ?', 'avatar' );
			$level_permissions = $permissionTable->fetchAll ( $select );
			
			foreach ( $values as $key => $value ) {
				
				$select = $permissionTable->select ()->where ( 'level_id = ?', $level_id )->where ( 'type = ?', 'avatar' )->where ( 'name = ?', $key );
				$level_permission = $permissionTable->fetchRow ( $select );
				
				if ($level_permission) {
					if ($value == 'none')
						$value = 0;
					
					$level_permission->value = $value;
					$level_permission->params = null;
					$level_permission->save ();
				} else {
					$permission = $permissionTable->createRow ();
					$permission->level_id = $level_id;
					$permission->name = $key;
					$permission->type = 'avatar';
					
					if ($value != "0" && $value != "1" && $value != "2") {
						$permission->value = 1;
						$permission->params = null;
					} else
						$permission->value = $value;
					
					$permission->save ();
				}
			}
		}
	}
}